package com.mengdie.shuidi.ui.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.mengdie.shuidi.AppContext;
import com.mengdie.shuidi.OkHeader;
import com.mengdie.shuidi.R;
import com.mengdie.shuidi.helper.UIHelper;
import com.mengdie.shuidi.manager.MDAccountMgr;
import com.mengdie.shuidi.model.BaseModel;
import com.mengdie.shuidi.model.PackageEntity;
import com.mengdie.shuidi.model.UserEnetity;
import com.mengdie.shuidi.ui.activity.PackageTypeActivity;
import com.mengdie.shuidi.ui.activity.ReplacePhoneActivity;
import com.mengdie.shuidi.ui.adapter.PackageAdapterV2;
import com.mengdie.shuidi.utils.ToastUtil;
import com.mengdie.shuidi.utils.core.EmptyUtils;
import com.orhanobut.logger.Logger;

import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by apple on 16/10/11.
 */

public class PayFragment extends Fragment {
    @Bind(R.id.rl_title_all)
    RelativeLayout mRlTitleAll;
    @Bind(R.id.rl_generic_back)
    RelativeLayout mRlGenericBack;
    @Bind(R.id.tv_generic_title)
    TextView mTvGenericTitle;
    @Bind(R.id.rv_pay_list)
    RecyclerView mRvPayList;
    @Bind(R.id.rl_go_bind_phone)
    RelativeLayout mRlGoBindPhone;
    private View rootView;
    private List<PackageEntity> packageList = new ArrayList<>();
    private PackageAdapterV2 mPackageAdapter;

    private UserEnetity userInfo;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.activity_pay, container, false);
            ButterKnife.bind(this, rootView);
            getBarHeight();
            init();
        }
        ViewGroup parent = (ViewGroup) rootView.getParent();
        if (parent != null) {
            parent.removeView(rootView);
        }
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onStart() {
        super.onStart();
        getUserInfo();
    }

    public void init() {
        mTvGenericTitle.setText("套餐购买");
        mRlGenericBack.setVisibility(View.GONE);
        mPackageAdapter = new PackageAdapterV2(packageList);
        mRvPayList.setLayoutManager(new LinearLayoutManager(getActivity()));
        mRvPayList.setAdapter(mPackageAdapter);
        mRvPayList.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {

            }

            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                super.onItemChildClick(adapter, view, position);
                switch (view.getId()) {
                    case R.id.tv_package_submit:
                        showPackagePayPage(getActivity(), packageList.get(position).getId() + "", packageList.get(position).getName());
                        break;
                }
            }
        });
        getPackageList();
    }


    public static void showPackagePayPage(Activity activity, String id, String type) {
        Intent intent = new Intent(activity, PackageTypeActivity.class);
        intent.putExtra(UIHelper.PACKAGE_ID, id);
        intent.putExtra(UIHelper.TYPE, type);
        activity.startActivity(intent);
    }

    private void getPackageList() {
        OkGo.getInstance().addCommonHeaders(OkHeader.getCommonHeadToken(getActivity()))
                .post(AppContext.getInstance().getBaseUrl() + "buy/packages")
                .params("pak_origin", "4")
                .tag("pay")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Gson gson = new Gson();
                        Type packageType = new TypeToken<BaseModel<List<PackageEntity>>>() {
                        }.getType();
                        BaseModel<List<PackageEntity>> packList;
                        try {
                            packList = gson.fromJson(s, packageType);
                        } catch (JsonSyntaxException e) {
                            packList = gson.fromJson(s, BaseModel.class);
                        }
                        if (packList.getRet().equals("0")) {
                            packageList = packList.getData();
                            mPackageAdapter.setNewData(packageList);
                        } else {
                            ToastUtil.showToast(packList.getMsg());
                        }

                    }
                });
    }

    /**
     * 获取用户信息
     */
    public void getUserInfo() {
        OkGo.getInstance().addCommonHeaders(OkHeader.getCommonHeadToken(getActivity()))
                .post(AppContext.getInstance().getBaseUrl() + "account/get_user_all")
                .tag(getActivity())
                .upJson(mapSession())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Logger.e("用户信息:" + s);
                        Gson gson = new Gson();
                        Type userType = new TypeToken<BaseModel<UserEnetity>>() {
                        }.getType();
                        BaseModel<UserEnetity> baseModel;
                        try {
                            baseModel = gson.fromJson(s, userType);
                        } catch (JsonSyntaxException e) {
                            baseModel = gson.fromJson(s, BaseModel.class);
                        }
                        if (baseModel.getRet().equals("0")) {
                            userInfo = baseModel.getData();
                            if (EmptyUtils.isEmpty(baseModel.getData().getPhone())) {
                                mRlGoBindPhone.setVisibility(View.VISIBLE);
                            } else {
                                mRlGoBindPhone.setVisibility(View.GONE);
                            }


                        } else {
                            ToastUtil.showToast(baseModel.getMsg());
                        }
                    }
                });
    }

    /**
     * 网络请求参数
     *
     * @return
     */
    private String mapSession() {
        HashMap<String, String> map = new HashMap<>();
        map.put("session_id", MDAccountMgr.getInstance().getSessionId());
        JSONObject json = new JSONObject(map);
        return json.toString();
    }

    @OnClick({R.id.iv_del, R.id.rl_go_bind_phone})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_del:
                mRlGoBindPhone.setVisibility(View.GONE);
                break;
            case R.id.rl_go_bind_phone:
                Intent phone = new Intent(getActivity(), ReplacePhoneActivity.class);
                Bundle phoneb = new Bundle();
                phoneb.putString("phone", userInfo.getPhone());
                phoneb.putString("name", userInfo.getUsername());
                phone.putExtras(phoneb);
                startActivity(phone);
                break;
        }
    }


    /**
     * 获取状态栏高度——方法1
     */
    private void getBarHeight() {
        int statusBarHeight1 = -1;
//获取status_bar_height资源的ID
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            //根据资源ID获取响应的尺寸值
            statusBarHeight1 = getResources().getDimensionPixelSize(resourceId);
        }
        LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) mRlTitleAll.getLayoutParams();
        layoutParams.setMargins(0, statusBarHeight1, 0, 0);
        mRlTitleAll.setLayoutParams(layoutParams);
    }
}
